﻿#include "WRWorkTcpCommServerAffair.h"
#include "WRWorkTcpCommServerInterface.h"
#include "WRWorkTcpCommServerInterfaceActivator.h"

#include <QTextCodec>

//计数器。
int WRWorkTcpCommServerAffair::_counter = 1;

//初始化当前对象。
WRWorkTcpCommServerAffair::WRWorkTcpCommServerAffair(WRWorkTcpCommServerObject* owner, int index, WRWorkAffair* target)
    : m_refCnt(1)
{
    m_id = _counter;
    ++_counter;
    m_index = index;
    m_owner = owner;
    m_target = target;
    m_iiLen = 0;
}
//清理对象所占用的相关资源。
WRWorkTcpCommServerAffair::~WRWorkTcpCommServerAffair(void)
{
    for(int i = 0; i < m_iiLen; ++i)
    {
        Interface iiVal = m_iiArr[i];
        delete iiVal;
    }
    m_owner->deleteAffair(m_index);
}

//查询指定标识的工作处理者。
WRWorkTcpCommServerAffair::Interface WRWorkTcpCommServerAffair::queryWorkDealer(const QUuid& uuid)
{
    void* reference = m_target->queryWorkDealer(uuid);
    if (reference)
    {
        WRWorkTcpCommServerInterfaceActivator* activator = WRWorkTcpComm::selectServerInterface(uuid);
        if (activator)
        {
            int iiIdx = m_iiLen;
            Interface iiVal = activator->create(iiIdx, this, reference);
            m_iiArr[iiIdx] = iiVal;
            ++m_iiLen;
            return iiVal;
        }
    }
    return 0;
}
//查询指定标识的任务处理者。
WRWorkTcpCommServerAffair::Interface WRWorkTcpCommServerAffair::queryTaskDealer(const QUuid& uuid)
{
    void* reference = m_target->queryTaskDealer(uuid);
    if (reference)
    {
        WRWorkTcpCommServerInterfaceActivator* activator = WRWorkTcpComm::selectServerInterface(uuid);
        if (activator)
        {
            int iiIdx = m_iiLen;
            Interface iiVal = activator->create(iiIdx, this, reference);
            m_iiArr[iiIdx] = iiVal;
            ++m_iiLen;
            return iiVal;
        }
    }
    return 0;
}
//查询指定标识的数据源接口。
WRWorkTcpCommServerAffair::Interface WRWorkTcpCommServerAffair::queryDataSource(const QUuid& uuid)
{
    void* reference = m_target->queryDataSource(uuid);
    if (reference)
    {
        WRWorkTcpCommServerInterfaceActivator* activator = WRWorkTcpComm::selectServerInterface(uuid);
        if (activator)
        {
            int iiIdx = m_iiLen;
            Interface iiVal = activator->create(iiIdx, this, reference);
            m_iiArr[iiIdx] = iiVal;
            ++m_iiLen;
            return iiVal;
        }
    }
    return 0;
}
//查询指定标识的事件源接口。
WRWorkTcpCommServerAffair::Interface WRWorkTcpCommServerAffair::queryEventSource(const QUuid& uuid)
{
    void* reference = m_target->queryEventSource(uuid);
    if (reference)
    {
        WRWorkTcpCommServerInterfaceActivator* activator = WRWorkTcpComm::selectServerInterface(uuid);
        if (activator)
        {
            int iiIdx = m_iiLen;
            Interface iiVal = activator->create(iiIdx, this, reference);
            m_iiArr[iiIdx] = iiVal;
            ++m_iiLen;
            return iiVal;
        }
    }
    return 0;
}
//查询指示标识的状态源接口。
WRWorkTcpCommServerAffair::Interface WRWorkTcpCommServerAffair::queryStateSource(const QUuid& uuid)
{
    void* reference = m_target->queryStateSource(uuid);
    if (reference)
    {
        WRWorkTcpCommServerInterfaceActivator* activator = WRWorkTcpComm::selectServerInterface(uuid);
        if (activator)
        {
            int iiIdx = m_iiLen;
            Interface iiVal = activator->create(iiIdx, this, reference);
            m_iiArr[iiIdx] = iiVal;
            ++m_iiLen;
            return iiVal;
        }
    }
    return 0;
}

//执行关闭处理。
void WRWorkTcpCommServerAffair::shutdown(void)
{
    for(int i = 0; i < m_iiLen; ++i)
    {
        m_iiArr[i]->shutdown();
    }
}

//处理接收到数据。
void WRWorkTcpCommServerAffair::procData(const unsigned char* buf, int len)
{
    WR16u cmdType = WRBytes::read<WR16u>(buf);
    buf += 2;
    len -= 2;
    switch (cmdType)
    {
    case WRWorkTcpComm::WorkAffairIIQuery://接口查询
    {
        WR32s cmdSequence = WRBytes::read<WR32s>(buf);
        buf += 4;
        len -= 4;
        WR16u id = WRBytes::read<WR16u>(buf);
        buf += 8;
        len -= 8;
        QUuid uid = WRBytes::read<QUuid>(buf);
        //执行接口查询
        Interface interface = 0;
        for(int i = 0; i < m_iiLen; ++i)
        {
            Interface interface2 = m_iiArr[i];
            if (interface2->uuid() == uid)
            {
                interface = interface2;
                break;
            }
        }
        if (!interface)
        {
            switch (id)
            {
            case WRWorkTcpComm::StateSource:
                interface = queryStateSource(uid);
                break;
            case WRWorkTcpComm::EventSource:
                interface = queryEventSource(uid);
                break;
            case WRWorkTcpComm::DataSource:
                interface = queryDataSource(uid);
                break;
            case WRWorkTcpComm::TaskDealer:
                interface = queryTaskDealer(uid);
                break;
            case WRWorkTcpComm::WorkDealer:
                interface = queryWorkDealer(uid);
                break;
            default:
                break;
            }
        }
        //发送查询响应
        WRDataPacket* packet;
        if (interface)
        {
            QTextCodec* codec = QTextCodec::codecForName("UTF-8");
            QByteArray nameArray = codec->fromUnicode(interface->name());
            int fillLen = 0;
            if (nameArray.length() <= 4)
            {
                fillLen = 4 - nameArray.length();
            }
            else
            {
                int tmpLen = nameArray.length()  - 4;
                int remain = tmpLen % 8;
                if (remain > 0) fillLen = 8 - remain;
            }
            int cmdLen = 36 + nameArray.length() + fillLen;

            packet = WRDataPacket::create(cmdLen);
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            p += 4;
            WRBytes::write((WR32s)(cmdLen), p);//帧长度
            p += 4;
            WRBytes::write((WR16u)(m_owner->index()), p);//工作对象索引
            p += 2;
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectAffair, p);//类型（工作事务）
            p += 2;
            WRBytes::write((WR32s)(m_id), p);//工作事务标识
            p += 4;
            WRBytes::write((WR16u)(m_index), p);//工作事务索引
            p += 2;
            WRBytes::write((WR16u)WRWorkTcpComm::WorkAffairIIQuery, p);//类型（接口查询）
            p += 2;
            WRBytes::write((WR32s)(cmdSequence), p);//指令序号
            p += 4;
            WRBytes::write((WR16s)(interface->index()), p);//接口索引
            p += 2;
            WRBytes::write((WR16s)(nameArray.length()), p); //name
            p += 2;
            memcpy(p, nameArray.constData(), nameArray.length());
            p += nameArray.length();
            p += fillLen;
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p);//版本
            p += 4;
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p);//帧尾
        }
        else
        {
            packet = WRDataPacket::allocate<40>();
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            WRBytes::write((WR32s)(40), p + 4);//帧长度
            WRBytes::write((WR16u)(m_owner->index()), p + 8);//工作对象索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectAffair, p + 10);//类型（工作事务）
            WRBytes::write((WR32s)(m_id), p + 12);//工作事务标识
            WRBytes::write((WR16u)(m_index), p + 16);//工作事务索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkAffairIIQuery, p + 18);//类型（接口查询）
            WRBytes::write((WR32s)(cmdSequence), p + 20);//指令序号
            WRBytes::write((WR16s)(-1), p + 24);//接口索引
            WRBytes::write((WR16s)(0), p + 26); //name
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 32);//版本
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 36);//帧尾
        }
        if (!sendData(packet))
        {
            packet->release();
        }
    }
        break;
    case WRWorkTcpComm::WorkAffairIITreat://接口处理
    {
        WR16u index = WRBytes::read<WR16u>(buf);
        buf += 2;
        len -= 2;
        if (index < m_iiLen)
        {
            Interface iiVal = m_iiArr[index];
            iiVal->procData(buf, len);
        }
    }
        break;
    case WRWorkTcpComm::WorkAffairDispose://工作释放
        release();
        break;
    default:
        break;
    }
}
